<template>
	<view class="container">
		<tui-loading v-show="!pageData.loading"></tui-loading>
		<view class="page" v-show="pageData.loading">
			<!-- 购物车数据为空 -->
			<u-empty v-if="cartList.length === 0 && appInit.image" mode="car" :icon="appInit.image.cart_empty">
			</u-empty>
			<u-line></u-line>
			<view v-if="cartList.length !== 0" class="head-info">
				<view class="cart-total">
					<text>购物数量</text>
					<text class="active">{{ cartList.length }}</text>
					<text></text>
				</view>
				<view class="cart-edit" @click="handleToggleMode()">
					<view v-if="mode == 'normal'" class="normal fl-center">
						<view class="icon iconfont icon-bianji"></view>
						<view>管理</view>
					</view>
					<view v-if="mode == 'edit'" class="edit">
						<text>完成</text>
					</view>
				</view>
			</view>
			<view v-if="cartList.length !== 0" class="cart-list">
				<u-checkbox-group @change="handleCheckItem" v-for="(item, index) in cartList" :key="index">
					<view class="cart-item">
						<view class="item-radio">
							<u-checkbox :name="item.id" :modelValue="tui.inArray(item.id, checkedIds)" shape="circle" />
						</view>
						<view class="goods-image" @click="onTargetGoods(item.obj_info.id)">
							<image class="image" :src="item.obj_info.picture.url" mode="scaleToFill"></image>
						</view>
						<view class="item-content">
							<view class="goods-title" @click="onTargetGoods(item.obj_info.id)">
								<text class="twoline-hide">{{item.obj_info.title}}</text>
							</view>
							<view class="goods-props clearfix">
								<view class="goods-props-item" v-for="(keysItem,keysIndex) in item.obj_info.keys" :key="keysIndex" v-if="item.obj_info.keys">
									<!-- <text>{{ props.value.name }}</text> -->
									<view class="">
										{{keysItem}}
									</view>
								</view>
							</view>
							<view class="item-foot">
								<view class="goods-price">
									<text class="unit">￥</text>
									<text class="value">{{item.price}}</text>
								</view>
								<view class="stepper">
									<tui-numberbox :value="item.num" :height="36" :width="64" :min="1" :index="index" @change="changeNum"></tui-numberbox>
									<!-- <u-number-box :min="1" :modelValue="item.num" :step="1" @change="changeNum" bgColor="#FFFFFF" color="#333333" /> -->
								</view>
							</view>
						</view>
					</view>
				</u-checkbox-group>
			</view>
			<!-- 底部操作栏 -->
			<view v-if="cartList.length !== 0" class="footer-fixed">
				<view class="all-radio">
					<u-checkbox-group @change="handleCheckAll">
						<u-checkbox :modelValue="checkedIds.length > 0 && checkedIds.length === cartList.length" shape="circle"></u-checkbox>
					</u-checkbox-group>
					<span>全选 {{ checkedIds.length > 0 ? `(${checkedIds.length})` : '' }}</span>
				</view>
				<view class="total-info">
					<!-- <view>合计：</view> -->
					<view class="goods-price">
						<view class="unit">￥</view>
						<view class="value">{{ pageData.totalPrice }}</view>
					</view>
				</view>
				<view class="cart-action">
					<view class="btn-wrapper">
						<!-- dev:下面的disabled条件使用checkedIds.join方式判断 -->
						<!-- dev:通常情况下vue项目使用checkedIds.length更合理, 但是length属性在微信小程序中不起作用 -->
						<view v-if="mode == 'normal'" class="btn-item btn-main" :class="{ disabled: checkedIds.join() == '' }" @click="handleOrder()">
							<text>立即下单</text>
						</view>
						<view v-if="mode == 'edit'" class="btn-item btn-main" :class="{ disabled: !checkedIds.length }" @click="handleDelete()">
							<text>删除</text>
						</view>
					</view>
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				get: {},
				pageData: {
					loading: false,
					isAll: false,
					isEdit: false,
					cartNum: 0,
					buyNum: 0,
					totalPrice: 0,
					totalIntegral: 0,
				},
				cartList: [],
				appInit: {},
				user: {},


				// 正在加载
				isLoading: true,
				// 当前模式: normal正常 edit编辑
				mode: 'normal',
				appThemeStyle: {
					mainBg: '#fa2209',
					mainBg2: '#ff6335',
					mainText: '#ffffff',
					viceBg: '#ffb100',
					viceBg2: '#ffb900',
					viceText: '#ffffff',
				},
				// 购物车商品列表
				list: [{
						id: '001',
						goods_id: '123456',
						goods: {
							goods_image: '../static/index/index_list1.png',
							goods_name: '哇哈哈',
							skuInfo: {
								goods_price: 888,
								goods_props: [{
									value: {
										name: '666'
									}
								}]
							}
						}
					},
					{
						id: '002',
						goods_id: '1234567',
						goods: {
							goods_image: '../static/index/index_list2.png',
							goods_name: '哇哈哈1',
							skuInfo: {
								goods_price: 989,
								goods_props: [{
									value: {
										name: '666'
									}
								}]
							}
						}
					},
				],
				// 购物车商品总数量
				// 选中的商品ID记录
				checkedIds: [],
				// 选中的商品总金额
			}
		},
		// 监听页面加载，其参数为上个页面传递的数据，参数类型为 Object（用于页面传参）
		onLoad(e) {
			let that = this;
			// uni.startPullDownRefresh();
			console.log("self:onLoad++++++++++++++++++++++++++++++++++++++++++++++++++");
			uni.stopPullDownRefresh(); //停止当前页面下拉刷新
			if (typeof(e.scene) != 'undefined') {
				e = that.tui.getUrlkey(decodeURIComponent(e.scene));
			}
			that.get = e;
			that.$forceUpdate();
		},
		// 监听页面显示。页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面
		onShow() {
			let that = this;
			that.initialize();
		},
		methods: {
			handleToggleMode() {
				this.mode = this.mode == 'normal' ? 'edit' : 'normal'
			},
			// 点击去逛逛按钮, 跳转到首页
			onTargetIndex() {
				this.tui.urlTab('pages/index/index');
			},
			onTargetGoods(goodsId) {
				this.tui.urlHref('pages/goods/detail', { goodsId })
			},
			// 选中商品
			handleCheckItem(e) {
				this.checkedIds = e;
			},
			handleCheckAll() {
				const { checkedIds, cartList } = this
				this.checkedIds = checkedIds.length === cartList.length ? [] : cartList.map(item => item.id)
			},
			initialize() {
				let that = this;
				let Int = setInterval(function() {
					that.user = that.tui.getCache("user");
					console.log('self:user=>', that.user);
					if (typeof(that.user) == 'object') {
						clearInterval(Int);
						that.__init();
					}
				}, 800);
			},
			async __init() {
				let that = this;
				that.appInit = that.tui.getCache("appInit");
				console.log('self:appInit=>', that.appInit);
				let response = '';
				response = await that.tui.get('/goods', {
					cart: that.tui.formatDate().timestamp,
				});
				that.cartList = response.data.data;
				that.initPrice();
				that.pageData.loading = true;
			},
			async changeNum(e) {
				let that = this;
				let response = '';
				let param = {
					cart_id: [that.cartList[e.index].id],
					num: [e.value],
				};
				response = await that.tui.put('/goods', param, {
					cart: that.tui.formatDate().timestamp,
				});
				switch (response.status) {
					case 0:
						that.cartList[e.index].num = e.value
						that.initPrice();
						break;
					default:
						break;
				}
			},
			handleOrder() {
				let that = this;
				let payIdArr = [];
				that.cartList.map((item) => {
					if (that.tui.inArray(item.id, that.checkedIds)) {
						payIdArr.push(item.id);
					}
				});
				if (payIdArr.length === 0) {
					that.tui.toast('请选择需要购买的商品~');
					return;
				}
				that.tui.setCache('goodsBuyCache', {
					type: 'cart',
					id: payIdArr,
				}, function() {
					that.tui.urlHref('/pages/index-confirm?' + that.tui.initParamsData({
						title: '商城下单',
						tpl: 'cartPay',
					}));
				});
			},
			handleDelete() {
				let that = this;
				let deleteIdArr = [];
				that.cartList.map((item) => {
					if (that.tui.inArray(item.id, that.checkedIds)) {
						deleteIdArr.push(item.id);
					}
				});
				if (deleteIdArr.length === 0) {
					that.tui.toast('请选择需要删除的商品~');
					return;
				}
				uni.showModal({
					title: '友情提示',
					content: '您确定要删除该商品吗？',
					showCancel: true,
					success({ confirm }) {
						// 确认删除
						that.tui.del('/goods', {
							cart_id: deleteIdArr,
						}, {
							cart: that.tui.formatDate().timestamp,
						}).then(function(delGoodsCartResponse) {
							switch (delGoodsCartResponse.status) {
								case 0:
									that.cartList = cartList;
									that.initPrice();
									break;
								default:
									break;
							}
						});
					}
				})
			},
			async detail(type, item = {}) {
				let that = this;
				console.log(type, item);
				switch (type) {
					default:
						break;
				}
			},
			initPrice() {
				let that = this;
				let cartNum = 0;
				let buyNum = 0;
				let totalPrice = 0;
				let totalIntegral = 0;
				let selectedNum = 0;
				that.cartList.map((item) => {
					if (that.tui.inArray(item.api_is_checked, [1])) {
						buyNum += item.num;
						totalPrice += item.price * item.num;
						totalIntegral += item.integral * item.num;
						selectedNum++
					}
					cartNum += item.num;
				})
				that.pageData.cartNum = cartNum;
				that.pageData.isAll = (selectedNum === that.cartList.length);
				that.pageData.buyNum = buyNum;
				if (totalPrice > 0) {
					totalPrice = (totalPrice * 100 / 100).toFixed(2);
				}
				that.pageData.totalPrice = totalPrice;
				that.pageData.totalIntegral = totalIntegral;
				that.$forceUpdate();
			},
			back() {
				let that = this;
				that.tui.urlBack(1);
			},
		},
	}
</script>

<style scoped lang="scss">
	.container {
		padding-bottom: 120rpx;
	}

	// 页面顶部
	.head-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 4rpx 30rpx;
		background-color: #fff;
		height: 80rpx;

		.cart-total {
			font-size: 24rpx;
			color: #333333;

			.active {
				color: #36B184;
				margin: 0 10rpx;
			}
		}

		.cart-edit {
			padding-left: 20rpx;

			.icon {
				margin-right: 12rpx;
			}

			.edit {
				color: #333333;
			}
		}

	}

	/deep/ .u-number-box__plus {
		border: 1px solid #999999 !important;
		width: 54rpx !important;
		height: 40rpx !important;
		border-radius: 0rpx 10rpx 10rpx 0rpx !important;
	}

	/deep/ .u-number-box__minus {
		border: 1px solid #999999 !important;
		border-radius: 10rpx 0rpx 0rpx 10rpx !important;
		width: 54rpx !important;
		height: 40rpx !important;
	}

	/deep/ .u-number-box__input {
		border-top: 1px solid #999999 !important;
		border-bottom: 1px solid #999999 !important;
		margin: 0 !important;
		width: 54rpx !important;
		height: 36rpx !important;
	}

	// 购物车列表
	.cart-list {
		padding: 0 16rpx 0 16rpx;
	}

	.cart-item {
		background: #fff;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		padding: 30rpx 16rpx;
		margin-bottom: 24rpx;
		margin: 20rpx 0;

		.item-radio {
			width: 56rpx;
			height: 80rpx;
			margin-right: 10rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.goods-image {
			width: 166rpx;
			height: 166rpx;

			.image {
				display: block;
				width: 100%;
				height: 100%;
				border-radius: 8rpx;
			}
		}

		.item-content {
			flex: 1;
			padding-left: 24rpx;

			.goods-title {
				font-size: 28rpx;
				max-height: 76rpx;
			}

			.goods-props {
				margin-top: 14rpx;
				color: #ababab;
				font-size: 24rpx;
				overflow: hidden;

				.goods-props-item {
					padding: 4rpx 16rpx;
					border-radius: 12rpx;
					// background-color: #fcfcfc;
				}
			}

			.item-foot {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 20rpx;

				.goods-price {
					// vertical-align: bottom;
					display: flex;
					align-items: center;
					color: #FE6850;

					.unit {
						font-size: 24rpx;
					}

					.value {
						font-size: 32rpx;
					}
				}
			}

		}
	}

	.normal {
		width: 100rpx;
		height: 38rpx;
		border: 1px solid #666666;
		font-weight: 500;
		font-size: 24rpx;
		color: #333333;
	}

	.fl-center {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	// 空数据按钮
	.empty-ipt {
		margin: 0 auto;
		width: 250rpx;
		height: 70rpx;
		font-size: 32rpx;
		text-align: center;
		color: #fff;
		border-radius: 50rpx;
		// background: linear-gradient(to right, $main-bg, $main-bg2);
		color: #333333;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	// 底部操作栏
	.footer-fixed {
		display: flex;
		align-items: center;
		height: 96rpx;
		background: #fff;
		padding: 0 30rpx;
		position: fixed;
		bottom: var(--window-bottom);
		left: 0;
		right: 0;
		z-index: 11;

		.all-radio {
			width: 200rpx;
			display: flex;
			align-items: center;

			.radio {
				margin-bottom: -4rpx;
				transform: scale(0.76)
			}
		}

		.total-info {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			padding-right: 30rpx;

			.goods-price {
				display: flex;
				align-items: center;
				color: #FE6850;
				font-size: 34rpx;
				.unit {
					font-size: 28rpx;
				}

				.value {
					font-size: 32rpx;
				}
			}
		}

		.cart-action {
			width: 200rpx;

			.btn-wrapper {
				height: 100%;
				display: flex;
				align-items: center;
			}

			.btn-item {
				flex: 1;
				font-size: 28rpx;
				height: 72rpx;
				color: #fff;
				border-radius: 50rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			// 去结算按钮
			.btn-main {
				// background: linear-gradient(to right, $main-bg, $main-bg2);
				font-size: 30rpx;
				color: #FFFFFF;
				width: 186rpx;
				height: 54rpx;
				background: #36B184;
				border-radius: 27rpx;

				// 禁用按钮
				&.disabled {
					opacity: 0.6;
				}
			}

		}

	}
</style>